package com.zj.docker.controller;


import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.Image;
import com.spotify.docker.client.messages.ImageInfo;
import com.zj.docker.client.LogClient;
import com.zj.docker.component.DockerComponent;
import com.zj.docker.component.UserRoleAuthentication;
import com.zj.docker.enums.CommonEnum;
import com.zj.docker.enums.RoleEnum;
import com.zj.docker.service.ImagesInfoService;
import com.zj.docker.utils.ResultVoUtil;
import com.zj.docker.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.*;

/**
 * @Auther: zj
 * @Date: 2018/11/29 13:54
 * @Description:
 */
@RestController
public class TestController {

    @Autowired
    UserRoleAuthentication userRoleAuthentication;
    @Autowired
    DockerComponent docker;
    @Autowired
    ImagesInfoService imagesInfoService;
    @Autowired
    LogClient logClient;

    @Value("${docker.Url}")
    private String dockerUrl; //docker的ip地址+端口号

    @GetMapping("/listImages")
    public ResultVo listImages(HttpServletRequest request) throws DockerException, InterruptedException {

//        String username = tokenComponent.getUsernameFromRequest( request );
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.Admin.getMessage());
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }

        // Create a client  by using the builder 通过builder连接一个客户机
        final DockerClient docker = DefaultDockerClient.builder()
                .uri( URI.create(dockerUrl) ) //2375端口，是centos7打开的远程访问端口，自己可自行设计
                // Set various options
                .build();

        final List<Image> quxImages = docker.listImages( DockerClient.ListImagesParam.allImages());
        System.out.println( quxImages.get( 0 ).repoTags() );

        return ResultVoUtil.success( quxImages.toString() );
    }

    @GetMapping("/test/111")
    public void test111111() throws InterruptedException {
        imagesInfoService.task1();
        imagesInfoService.task2();
        imagesInfoService.task3();

    }

    @GetMapping("/test/222")
    public void test22222() {
        logClient.createLog( "1","2","1",1,"",
                "","","","","","","");
    }




}
